import {Component, ElementRef, HostListener, ViewChild} from '@angular/core';
import {
    IonicPage, Loading, MenuController, NavController, Platform, LoadingController, Content
} from 'ionic-angular';
import {LoginProvider} from "../../providers/login/login";
import {ToastController} from 'ionic-angular';
import {PermissionsService} from "../../services/native/permissions/permissions.service"
import {UnlockService} from '../../services/native/authentication/authentication.service';
/*import {CaptchaService} from '../../services/common/captcha.service';*/
import {FileService} from "../../services/native/file/file.service";
import {LoadingService} from "../../services/common/loading.service";
import {ToastService} from "../../services/common/toast.service";
import {JPushControlerService} from "../../services/native/push/jpush-controler.service";

@IonicPage()
@Component({
    selector: 'page-login',
    templateUrl: 'login.html',
    providers: [
        PermissionsService,
        FileService,
        LoadingService
    ]
})
export class LoginPage {

    isDisabled: boolean = true;    // 禁用登录按钮
    isUserNameEmpty: boolean = true;
    isPasswordEmpty: boolean = true;
    loading: Loading;
    mainHeight: number;
    @ViewChild('username') usernameInput: HTMLInputElement;
    @ViewChild('mainContainer') mainContainer: ElementRef;
    @ViewChild('forgetPassword') forgetPasswordRef: ElementRef;
    @ViewChild(Content) content: Content;
    @ViewChild('loginInBtn') loginBtnRef: ElementRef;
    @ViewChild('logoContainer') logoRef:ElementRef;
    @ViewChild('inputContainer') inputContainerRef:ElementRef;

    constructor(public navCtrl: NavController,
                public loginProvider: LoginProvider,
                public toastCtrl: ToastController,
                private permissionsService: PermissionsService,
                private menuCtrl: MenuController,
                private fileService: FileService,
                private unlockService: UnlockService,
           /*     private captchaService: CaptchaService,*/
                private platform: Platform,
                private jPushControlerService: JPushControlerService,
                public loadCtr: LoadingController,
                private toastService: ToastService) {
    }

    ionViewWillEnter() {
        this.jPushControlerService.stopPush();
        this.jPushControlerService.setAliasNull();
    }

    /**
     * 输入变更
     * @param username
     * @param password
     */
    inputChange(username, password) {
        this.isUserNameEmpty = username.value.length === 0;
        this.isPasswordEmpty = password.value.length === 0;
        this.isDisabled = this.isUserNameEmpty || this.isPasswordEmpty; // || !this.isCaptchaPassed;
        if (username.value.length > 0) {
            let result = /^[A-Za-z0-9\s]+$/g.test(username.value);
            if (!result) {
                this.toastCtrl.create({
                    message: "请输入正确的用户名",
                    duration: 1200,
                    position: 'bottom'
                }).present().then(() => {
                    username.value = username.value.replace(/[^A-Za-z0-9\s]*/g, "");
                    username.initFocus();
                });
            }
        }
    }

    /**
     * 用户名输入框失去焦点事件
     */
    userNameBlur(username) {
        if (username.value.length > 0) {
            let curUserName = decodeURI(encodeURI(username.value).replace(/%E2%80%86/g, ""));
            curUserName = curUserName.toUpperCase();
            username.value = curUserName;
        }

    }

    /**
     * 登录
     * @param {HTMLInputElement} username
     * @param {HTMLInputElement} password
     */
    logIn(username: HTMLInputElement, password: HTMLInputElement) {
        $('.name-input input').blur();
        $('.psd-input input').blur();
        this.isDisabled = true;
        setTimeout(() => {
            let userName = username.value.trim(),
                realPassword = password.value;
            localStorage.setItem('requestId', 'test');
            if (userName.length > 0 && realPassword.length > 0) {
                this.showLoading();
                localStorage.setItem('ReLoginFlag','true');
                this.unlockService.login(userName, realPassword).then(() => {
                    this.dismissLoading();
                    //记录提醒状态
                    localStorage.setItem('tokenExpireUpdated', '0');
                    this.navCtrl.setRoot('TabsPage');
                    //移除重新登录标记
                    localStorage.removeItem('ReLoginFlag');
                    this.isDisabled = false;
                }, error => {
                    this.dismissLoading();
                    if (error.status === 401 || error.status === 500) {
                        console.log("login error!!!");
                        this.toastCtrl.create({
                            message: window['unescape'](error.error.error_description.replace(/\\u/g, '%u')),
                            position: 'middle',
                            duration: 1200
                        }).present();
                    }
                    this.isDisabled = false;
                })
            } else {
                this.toastCtrl.create({
                    message: "您输入的用户名或密码有误",
                    position: 'middle',
                    duration: 1200
                }).present()
                this.isDisabled = false;
            }
        }, 200);
    }

    ionViewDidLoad() {
        if (this.platform.is('cordova')) {
            if (this.platform.is('android')) {
                this.permissionsService.getAndroidPermission();
            } else {
                this.permissionsService.getIosPermission();
            }
        }

        this.menuCtrl.enable(false);
    }

    /**
     * 显示加载提示
     */
    showLoading() {
        this.loading = this.loadCtr.create({
            spinner: 'circles',
            content: "正在登录，请稍等"
        });
        this.loading.present();
    }

    /**
     * 关闭加载提示
     */
    dismissLoading() {
        if (this.loading) {
            this.loading.dismiss();
        }
    }

    ionViewWillLeave() {
        /*this.captchaService.hide();*/
    }

    ionViewDidEnter() {
        this.unlockService.graphicErrorTimes().then((errorTime) => {
            if (errorTime === 5) {
                //如果是手势输错密码5次，则不需要输入用户名，以及验证码
                this.usernameInput.value = this.unlockService.getCurrentUser();
            } else {
                // localStorage.setItem('requestId','test');

                //打开验证码输入框
                //this.captchaService.show();
            }
        });
        this.setForgetPasswordHeight();
    }

    @HostListener("document:resume")
    onAppResume() {
        this.jPushControlerService.clearBadge();
    }

    forgetPasswordClick() {
        this.toastService.showToast("请至AWS修改密码后重新登录", 3000);
    }

    setForgetPasswordHeight() {
        setTimeout(() => {
            let allHeight = this.mainContainer.nativeElement.scrollHeight;
            let logoHeight = this.logoRef.nativeElement.scrollHeight; //logo
            let inputHeight = this.inputContainerRef.nativeElement.scrollHeight;//input height
            let btnHeight = this.loginBtnRef.nativeElement.scrollHeight;
            let emptyHeight = allHeight -logoHeight - inputHeight - btnHeight - ((160 * allHeight) / 1920) ;
            this.mainHeight = allHeight;
            this.forgetPasswordRef.nativeElement.setAttribute('style', 'margin-top:' + emptyHeight + "px");
        }, 0);
    }

    skipToPostion(e) {
        const top = e.target.offsetParent.offsetTop;
        if (this.platform.is('ios')) {
            let emptyHeight = 140;
            this.mainContainer.nativeElement.setAttribute('style', 'height:' + (this.mainHeight - emptyHeight) + "px");
            setTimeout(() => {
                this.content.scrollTo(0, top);
            }, 500);
        }
    }

}
